﻿using Goway.Log4net;
using Goway.StackingUC.Entity;
using Goway.StackingUC.Forms;
using Goway.StackingUC.Modules;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Goway.StackingUC
{
    public partial class FrmMain : UIForm
    {
        /// <summary>
        /// 是否点击了“关闭”按钮
        /// </summary>
        private bool isCloseButtonClick;

        /// <summary>
        /// 选择的库区编号
        /// </summary>
        private int selectedAreaId;

        /// <summary>
        /// 堆垛机
        /// </summary>
        private StackingControllerTest stackingController;

        /// <summary>
        /// 页面显示的数据
        /// </summary>
        private List<MaterialInfo> materials;

        public FrmMain()
        {
            InitializeComponent();

            isCloseButtonClick = false;
        }

        private void timerMessage_Tick(object sender, EventArgs e)
        {
            MarqueeMessage.ShowMarqueeMessage_Tick(this);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.ShowMarqueeMessage("页面加载中...");

            // 自动换行
            this.dgvMaterials.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            // 不自动加载多余数据
            this.dgvMaterials.AutoGenerateColumns = false;
            this.dgvMaterials.MultiSelect = false;

            // 去掉列表头排序
            foreach (DataGridViewColumn item in dgvMaterials.Columns)
            {
                item.SortMode = DataGridViewColumnSortMode.NotSortable;
                item.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }

            // 设定包括Header和所有单元格的列宽自动调整
            //this.dgvMaterials.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            // 初始化堆垛机
            this.stackingController = new StackingControllerTest("192.168.0.1");

            stackingController.ShowWndMessage += StackingController_ShowWndMessage;
            stackingController.RefrushMaterialInfo += StackingController_RefrushMaterialInfo;

            if(!stackingController.Initialization(out string errorMsg))
            {
                this.ShowMessage("堆垛机初始化失败！");
                return;
            }

            // 运行堆垛机程序
            ModuleManager.GetInstance().AddRunFunction("StackingWork", stackingController.StackingDoWork);
            ModuleManager.GetInstance().AddRunFunction("SendHeartbeat", stackingController.SendHeartbeat);

            InitMaterials();
            this.dgvMaterials.DataSource = materials;
            this.dgvMaterials.ClearSelection();
        }

        /// <summary>
        /// 初始化物料信息
        /// </summary>
        private void InitMaterials()
        {
            MaterialRecord record = new MaterialRecord();
            this.materials = record.GetMaterials();
        }

        /// <summary>
        /// 刷新页面
        /// </summary>
        /// <param name="materials"></param>
        private void StackingController_RefrushMaterialInfo(List<MaterialInfo> materialInfos)
        {
            if(materials == null || materials.Count == 0)
            {
                return;
            }

            int length = this.materials.Count > materialInfos.Count ? materialInfos.Count : materials.Count;
            for(int i = 0; i < length; i++)
            {
                this.materials.ElementAt(i).RowIndex = materialInfos.ElementAt(i).RowIndex;
                this.materials.ElementAt(i).ColumnIndex = materialInfos.ElementAt(i).ColumnIndex;
                this.materials.ElementAt(i).LayerIndex = materialInfos.ElementAt(i).LayerIndex;
                this.materials.ElementAt(i).AtLocation = materialInfos.ElementAt(i).AtLocation;
            }

            try
            {
                if (this.Created)                   // 页面未加载时不能显示信息
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        this.dgvMaterials.Rows.Clear();

                        this.dgvMaterials.DataSource = this.materials;
                        this.dgvMaterials.ClearSelection();
                    }));
                }
            }
            catch(Exception ex)
            {
                LoggerHelper.Error($"刷新界面物料位置异常！{ex.Message}");
                return;
            }
        }

        /// <summary>
        /// 堆垛机消息通知显示
        /// </summary>
        /// <param name="message"></param>
        private void StackingController_ShowWndMessage(string message)
        {
            this.ShowMarqueeMessage(message);
            this.ShowMessage(message);
        }

        /// <summary>
        /// 入库测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInputBarcode_Click(object sender, EventArgs e)
        {
            if(selectedAreaId <= 0)
            {
                this.ShowMessage("请选择库区！");
                this.ShowMarqueeMessage("请选择库区！");
            }

            // 向所选择库区增加物料
            if (string.IsNullOrEmpty(this.txtBarcode.Text.Trim()))
            {
                this.ShowMessage("请录入物料条码！");
                this.ShowMarqueeMessage("请录入物料条码！");
            }
        }

        /// <summary>
        /// 键盘按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnInputBarcode_Click(null, null);
            }
        }

        private void cmbArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbArea.SelectedValue != null)
            {
                this.selectedAreaId = (int)this.cmbArea.SelectedValue;
            }
        }

        /// <summary>
        /// 获得消息显示框
        /// </summary>
        /// <returns></returns>
        public UIRichTextBox GetMessageBox() => this.txtMessage;

        private void btnClose_Click(object sender, EventArgs e)
        {
            isCloseButtonClick = true;
            FrmTips frm = new FrmTips("确定停止堆垛机上位程序，退出系统吗？");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.Close();
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isCloseButtonClick)
            {
                return;
            }

            FrmTips frm = new FrmTips("确定停止堆垛机上位程序，退出系统吗？");
            if (frm.ShowDialog() != DialogResult.OK)
            {
                e.Cancel = true;
            }

            isCloseButtonClick = false;
        }
    }
}
